package com.eipp.android.redlonjohnson;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import com.eipp.android.redlonjohnson.CustomHttpClient;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Context;
import android.content.ContextWrapper;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.os.StrictMode;
import android.text.method.LinkMovementMethod;
import android.text.util.Linkify;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Display;
import android.view.Menu;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity {
	
	TextView userId;
	TextView address; // To take birthyear as input from userdit
	int AccountNo;
	EditText password;
	 Button submit; 
	 String returnString;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
		  .detectDiskReads().detectDiskWrites().detectNetwork() // StrictMode is most commonly used to catch accidental disk or network access on the application's main thread
		  .penaltyLog().build());
		super.onCreate(savedInstanceState);
		Context mContext = getBaseContext();
		DisplayMetrics displayMetrics = new DisplayMetrics(); 
		displayMetrics = mContext.getResources().getDisplayMetrics();
		int mScreenWidth = displayMetrics.widthPixels;
		int mSreenHeight = displayMetrics.heightPixels;
         
		System.out.println("--display ================= "+ mScreenWidth + "-----" + mSreenHeight);
		setContentView(R.layout.activity_main);
		SharedPreferences pref = getApplicationContext().getSharedPreferences("MyPref", 0); // 0 - for private mode
		userId = (TextView) findViewById(R.id.username);
		userId.setText(pref.getString("UserName", null));
		address = (TextView) findViewById(R.id.address);
		address.setText(pref.getString("Address", null));
		Log.i("karthiushak", pref.getString("Address", null)) ;
		//AccountNo = pref.getInt("AccountNo", (Integer) null);
		//Log.i("karthiaccount", new Integer(AccountNo).toString());
		ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
		postParameters.add(new BasicNameValuePair("AccountNo","11475"));
		 String response = null;
		 try {
        	 Log.i("mainkarthi", "hi"); 
    response = CustomHttpClient.executeHttpPost(
      //"http://10.0.2.2/jsonscript.php", // your ip address if using localhost server
      "https://eipp03.com/redlon1/invoice.php",  // in case of a remote server
      postParameters);
    System.out.println("mainkarthi ================= ");
    // store the result returned by PHP script that runs MySQL query
    String result = response.toString();  
    System.out.println("mainkarthi ================= "+ result);
       Log.i("mailkarthi", result);      
     //parse json data
        try{
                returnString = "";
          JSONArray jArray = new JSONArray(result);
        //String re=jArray.getString(jArray.length()-1);
          // int re = jArray.getInt(jArray.length()-1); 
       
          SimpleDateFormat df = new SimpleDateFormat("yyyy/mm/dd");
          
          String startDate = "06/27/2007";
          for(int i=0;i<jArray.length();i++){
              JSONObject json_data = jArray.getJSONObject(i);
             System.out.println("kkkkkkkkkdate========" +json_data.getString("InvoiceDate"));
            
            
              // json_data.put("InvoiceDate", "/Date(" + format.format(new Date()) + ")/");
              Log.i("log_kk","AccountNO: "+json_data.getInt("AccountNo"));
          }
           TableLayout tv=(TableLayout) findViewById(R.id.table);
           
            tv.removeAllViewsInLayout();
            
     	   int flag=1;
     	 
     	for(int i1=-1;i1<jArray.length();i1++)
     	        
     	        {
     	        	 
     	                TableRow tr=new TableRow(MainActivity.this);
     		            
     		            tr.setLayoutParams(new LayoutParams(mScreenWidth,mSreenHeight));
     		            tr.setPadding(5, 0, 0, 2);
     		            
     		           
     		            
     		            
     		         
     		            if(flag==1)
     		            {
     		            	
     		            	
     		            
     		            	
     		                TextView b19=new TextView(MainActivity.this);
     		                
     		                b19.setPadding(10, 0, 0, 0);
     		                 b19.setTextSize(15);
     		        	     b19.setText("Invoice No");
     		        	    //b19.setTextAppearance(getBaseContext(), R.style.HeaderText);
     		        	     b19.setTextColor(Color.BLACK);
     		        	     b19.setBackgroundColor(Color.RED);
     		        	     tr.addView(b19);
     		        	     
     		                 
     		               TextView b29=new TextView(MainActivity.this);
     		                 b29.setPadding(10, 0, 0, 0);
     		                 b29.setTextColor(Color.BLACK);
     		                 b29.setBackgroundColor(Color.RED);
     		        	     b29.setText("Invoice Date");
     		        	     b29.setTextSize(15);
     		                 tr.addView(b29);
     		                
     		                TextView b39=new TextView(MainActivity.this);
     		                 b39.setPadding(10, 0, 0, 0);
     		                 b39.setText("Amount");
     		                 b39.setTextColor(Color.BLACK);
    		                 b39.setBackgroundColor(Color.RED);
     		                 b39.setTextSize(15);
    		                 tr.addView(b39);
     		                 
     		                 tv.addView(tr);
     		            
     		        	     final View vline = new View(MainActivity.this);
     			       		   vline.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.FILL_PARENT, 5));
     			       		   vline.setBackgroundColor(Color.BLACK);
     			       		  
     		            
     		            
     		            tv.addView(vline);
     		            flag=0;
     		        
     		            	System.out.println("flahg=============" + flag);
     		            System.out.println("re=============" + jArray.length());
     		            	
     		            	
     		            	
     		            }
	            
     		            else
     		            {
     		            	
     		            
     		               System.out.println("iiiii=============" + i1);
     		            	final JSONObject json_data = jArray.getJSONObject(i1);
     		             final TextView b1=new TextView(MainActivity.this);
    	                b1.setPadding(5, 5, 5, 5);
    	                 String stime1=String.valueOf(json_data.getInt("InvoiceNo"));
    	             	 b1.setText(stime1);
    	             	b1.setBackgroundColor(R.style.BodyRow);
    	             	 b1.setOnClickListener(new View.OnClickListener() {
    							
    							@Override
    							public void onClick(View v) {
    								// TODO Auto-generated method stub
    							    Toast.makeText(getBaseContext(), "clicked", Toast.LENGTH_LONG).show();	
    							   try {
									   b1.setBackgroundColor(Color.GRAY);
    								   String url = "https://docs.google.com/gview?embedded=true&url=https://eipp03.com"+ json_data.getString("FilePath");
									
									startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(url)));
								} catch (JSONException e) {
									// TODO Auto-generated catch block
									e.printStackTrace();
								}
    							   // mWebView.loadUrl("https://docs.google.com/gview?embedded=true&url=https://eipp03.com/Scanner/Localuser/Redlon%20Johnson/2013/july/07122013/07_11_13-135727-inv.pdf");
    							    
    							}
    						});
    	        	     tr.addView(b1);
    	                 
    	              TextView b2=new TextView(MainActivity.this);
    	                 b2.setPadding(5, 5, 5, 5);
    	                 b2.setTextColor(Color.WHITE);
    	                 
    	        	     String stime2=String.valueOf(json_data.getString("InvoiceDate"));
    	        		 b2.setText(stime2);
    	        		 tr.addView(b2);
    	        	    
    	        	     TextView b3=new TextView(MainActivity.this);
    	                 b3.setPadding(5, 5, 5, 5);
    	        	     String stime3=String.valueOf(json_data.getString("Amount"));
    	        	     b3.setText("$"+ stime3);
    	        	     b3.setClickable(true);
    	        	     
    	        	     b3.setTextColor(Color.WHITE);
    	        	     //b3.setBackgroundColor(Color.GRAY);
    	        	     b3.setTextSize(15);
    	        	     tr.addView(b3);
    	                   tv.addView(tr);
     	            
     	            
    	         final View vline1 = new View(MainActivity.this);
    		   vline1.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.FILL_PARENT, 1));
    		   vline1.setBackgroundColor(Color.WHITE);
    		   tv.addView(vline1);		
     	         
        }
     	        }
        }
        catch(JSONException e){
                Log.e("log_tag", "Error parsing data "+e.toString());
                Toast.makeText(getBaseContext(), "Login Error loading Invoices", Toast.LENGTH_LONG).show();
                
               
        }
    
        try{
        
        }
        catch(Exception e){
         Log.e("log_tag","Error in Display!" + e.toString());;          
        }   
   }
         catch (Exception e) {
    Log.e("log_tag","Error in http connection!!" + e.toString());     
   }
        } 
		
	

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

}
